package cn.shentianlan.controller;

import cn.shentianlan.domain.User;
import cn.shentianlan.domain.UserTable;
import cn.shentianlan.service.UserService;
import cn.shentianlan.utils.CookieUtils;
import cn.shentianlan.utils.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 首次使用系统，实现管理员注册功能！
     * @param user
     * @return login.html（登陆界面）
     */
    @RequestMapping(value = "/registerUser.do",method = RequestMethod.POST)
    public ModelAndView registerUser(User user){
        userService.addUser(user);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:login.html");
        return modelAndView;
    }

    /**
     *  ajax校验用户名是否存在
     * @param gd_id
     * @return
     */
    @RequestMapping(value = "/findUserById.do")
    public void findUserById(@RequestParam(value="gd_id", required=false) String gd_id, HttpServletResponse response) throws IOException {
        User user = userService.findUserById(gd_id);
        if (user!=null){
            response.getWriter().write("true");
        }else {
            response.getWriter().write("false");
        }
    }

    /**
     * 用户登录
     * @param gd_id
     * @param gd_password
     * @param autoLoginFlag
     * @param response
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/loginUser.do")
    public String findUserController(@RequestParam(value="gd_id", required=false) String gd_id,
                               @RequestParam(value="gd_password", required=false) String gd_password,
                               @RequestParam(value = "autoLoginFlag",required = false) String autoLoginFlag,
                               HttpServletResponse response,HttpServletRequest request) throws IOException {

        HttpSession session = request.getSession();
        User user = userService.findUser(gd_id,gd_password);
        Cookie cookie = CookieUtils.getCookie(request,"autoLoginCookie");
        if (user!=null){
            //创建或更新cookie
            try {
                if (autoLoginFlag!=null && autoLoginFlag.equals("on")){
                    if (cookie!=null){
                        cookie.setValue(gd_id+"###"+gd_password);
                    }else {
                        cookie = new Cookie("autoLoginCookie",gd_id+"###"+gd_password);
                    }
                    cookie.setMaxAge(60*60*24*7);//设置cookie存活7天
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }else {
                    if (cookie != null) {
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                }
            }catch (Exception e){
                System.out.println(e.getMessage());
            }

            session.setAttribute("loginUser",user);
            return "/WEB-INF/pages/monitoring.jsp";
        }
        response.getWriter().write("false");
        return null;
    }

    /**
     * 表单数据显示
     * @param request
     * @return
     */
    @RequestMapping(value = "/showUser.do")
    public void findUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        int start = Integer.parseInt(request.getParameter("start"));//开始页数
        int length = Integer.parseInt(request.getParameter("length"));//查询数据的长度
        int draw = Integer.parseInt(request.getParameter("draw"));//查询次数
        String searchValue = request.getParameter("search.value");//要搜索数据的值
        UserTable userTable = userService.showUser(start,length,draw,searchValue);
        //将userTable转成json数据
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(userTable);
        response.getWriter().write(jsonString);
    }

    /**
     * 根据用户id删除用户
     * @param gd_id
     */
    @RequestMapping(value = "/deleteUser.do",method=RequestMethod.POST)
    public void deleteUser(@RequestParam("gd_id") String gd_id,HttpServletResponse response) throws IOException {
        boolean b = userService.deleteUser(gd_id);
        response.getWriter().print(b);
    }

    /**
     * 添加用户
     * @param user
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/addUser.do",method = RequestMethod.POST)
    public String addUser(User user,HttpServletResponse response) throws IOException {
        try{
            userService.addUser(user);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "/WEB-INF/pages/tables/userManage.jsp";
    }

    @RequestMapping(value = "/updateUser.do",method = RequestMethod.POST)
    public String updateUser(User user,HttpServletResponse response) throws IOException {
            userService.updateUser(user);
        return "/WEB-INF/pages/tables/userManage.jsp";
    }

    @RequestMapping(value = "logOutUser.do")
    public String logOutUser(HttpSession session,HttpServletRequest request,HttpServletResponse response){
        Cookie cookie = CookieUtils.getCookie(request,"autoLoginCookie");
        if (cookie!=null){
            cookie.setValue("");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        session.removeAttribute("loginUser");
        return "login.html";
    }

    @RequestMapping(value = "getUser.do",method = RequestMethod.POST)
    public void getUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String gd_id = request.getParameter("gd_id");
        String gd_password = request.getParameter("gd_password");
        User user = userService.findUser(gd_id, gd_password);
        if (user!=null){
            response.getWriter().write(JsonUtils.ObjectToString(user));
        }else {
            response.getWriter().write("false");
        }
    }
}
